import { Context } from '../../index'
import { useContext, useEffect, useRef, useState } from 'react'
import classNames from 'classnames'

// 任务列表每一项组件
const TodoItem = ({ item }) => {
  // 接受index.js方法
  const { delTodo, handleDone, changeName } = useContext(Context)

  // 双击显示输入框的参数
  const [current, setCurrent] = useState({
    id: '',
    name: '',
  })

  // 创建双击显示输入框的ref
  const inputRef = useRef(null)

  // 双击显示输入框自动获取焦点
  useEffect(() => {
    inputRef.current.focus()
  }, [current])

  // 双击修改任务名称
  const showEdit = (item) => {
    setCurrent({
      id: item.id,
      name: item.name,
    })
  }

  // 键盘按下事件
  const updataName = (e) => {
    if (e.keyCode === 27) {
      setCurrent({
        id: '',
        name: '',
      })
    }
    if (e.keyCode === 13) {
      changeName(current.id, current.name)
      setCurrent({
        id: '',
        name: '',
      })
    }
  }

  return (
    <li
      className={classNames({
        completed: item.isDone,
        editing: item.id === current.id,
      })}
      key={item.id}
    >
      <div className="view">
        <input
          className="toggle"
          type="checkbox"
          checked={item.isDone}
          onChange={() => handleDone(item.id)}
        />
        <label
          onDoubleClick={() => {
            showEdit(item)
          }}
        >
          {item.name}
        </label>
        <button
          className="destroy"
          onClick={() => {
            delTodo(item.id)
          }}
        ></button>
      </div>
      <input
        className="edit"
        value={current.name}
        ref={inputRef}
        onBlur={() => setCurrent({ id: '', name: '' })}
        onChange={(e) => setCurrent({ id: current.id, name: e.target.value })}
        onKeyUp={updataName}
      />
    </li>
  )
}

export default TodoItem
